package com.uniflow.service;

import com.uniflow.entity.UserPermission;
import com.uniflow.mapper.UserPermissionMapper;
import com.uniflow.util.AuditLogHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户权限服务层
 * 
 * @author luban
 * @since 1.0.0
 */
@Service
@Transactional
public class UserPermissionService {
    
    @Autowired
    private UserPermissionMapper userPermissionMapper;
    
    @Autowired
    private AuditLogHelper auditLogHelper;
    
    /**
     * 根据ID查询用户权限
     */
    public UserPermission getUserPermissionById(String id) {
        return userPermissionMapper.selectById(id);
    }
    
    /**
     * 根据用户ID查询权限列表
     */
    public List<UserPermission> getUserPermissions(String userId) {
        return userPermissionMapper.selectByUserId(userId);
    }
    
    /**
     * 根据权限ID查询用户列表
     */
    public List<UserPermission> getPermissionUsers(String permissionId) {
        return userPermissionMapper.selectByPermissionId(permissionId);
    }
    
    /**
     * 检查用户是否有指定权限
     */
    public boolean hasUserPermission(String userId, String permissionId) {
        return userPermissionMapper.hasUserPermission(userId, permissionId);
    }
    
    /**
     * 检查用户是否被授权指定权限
     */
    public boolean isUserPermissionGranted(String userId, String permissionId) {
        return userPermissionMapper.isUserPermissionGranted(userId, permissionId);
    }
    
    /**
     * 查询用户的权限ID列表
     */
    public List<String> getUserPermissionIds(String userId) {
        return userPermissionMapper.selectPermissionIdsByUserId(userId);
    }
    
    /**
     * 查询用户的已授权权限ID列表
     */
    public List<String> getGrantedPermissionIds(String userId) {
        return userPermissionMapper.selectGrantedPermissionIdsByUserId(userId);
    }
    
    /**
     * 查询用户的有效权限ID列表（未过期且已授权）
     */
    public List<String> getValidPermissionIds(String userId) {
        return userPermissionMapper.selectValidPermissionIdsByUserId(userId);
    }
    
    /**
     * 查询权限的用户ID列表
     */
    public List<String> getPermissionUserIds(String permissionId) {
        return userPermissionMapper.selectUserIdsByPermissionId(permissionId);
    }
    
    /**
     * 为用户授权权限
     */
    @Transactional
    public UserPermission grantPermission(String userId, String permissionId, String grantedBy, String reason) {
        return grantPermission(userId, permissionId, true, grantedBy, null, reason, null, false);
    }
    
    /**
     * 为用户授权临时权限
     */
    @Transactional
    public UserPermission grantTemporaryPermission(String userId, String permissionId, String grantedBy, 
                                                   String reason, LocalDateTime expiresAt) {
        return grantPermission(userId, permissionId, true, grantedBy, null, reason, expiresAt, true);
    }
    
    /**
     * 为用户授权权限（完整版）
     */
    @Transactional
    public UserPermission grantPermission(String userId, String permissionId, Boolean granted, String grantedBy, 
                                         String grantedByName, String reason, LocalDateTime expiresAt, Boolean temporary) {
        // 检查是否已存在
        UserPermission existing = userPermissionMapper.selectByUserIdAndPermissionId(userId, permissionId);
        if (existing != null) {
            // 如果已存在，更新授权信息
            existing.setGranted(granted);
            existing.setGrantedBy(grantedBy);
            existing.setGrantedByName(grantedByName);
            existing.setReason(reason);
            existing.setExpiresAt(expiresAt);
            existing.setTemporary(temporary);
            existing.setGrantedAt(LocalDateTime.now());
            
            userPermissionMapper.updateById(existing);
            
            // 记录审计日志
            auditLogHelper.recordLog(
                granted ? "GRANT_USER_PERMISSION" : "REVOKE_USER_PERMISSION",
                "user_permission",
                userId + "-" + permissionId,
                (granted ? "授权" : "撤销") + "用户权限" + (temporary ? "(临时)" : ""),
                "success",
                grantedBy
            );
            
            return existing;
        }
        
        // 创建新的权限关联
        UserPermission userPermission = new UserPermission(userId, permissionId, granted, grantedBy, reason);
        userPermission.setId(UUID.randomUUID().toString().replace("-", ""));
        userPermission.setGrantedByName(grantedByName);
        userPermission.setExpiresAt(expiresAt);
        userPermission.setTemporary(temporary != null ? temporary : false);
        
        userPermissionMapper.insert(userPermission);
        
        // 记录审计日志
        auditLogHelper.recordLog(
            granted ? "GRANT_USER_PERMISSION" : "REVOKE_USER_PERMISSION",
            "user_permission",
            userId + "-" + permissionId,
            (granted ? "授权" : "撤销") + "用户权限" + (temporary ? "(临时)" : ""),
            "success",
            grantedBy
        );
        
        return userPermission;
    }
    
    /**
     * 撤销用户权限
     */
    @Transactional
    public void revokePermission(String userId, String permissionId, String operatorId, String reason) {
        grantPermission(userId, permissionId, false, operatorId, null, reason, null, false);
    }
    
    /**
     * 删除用户权限关联
     */
    @Transactional
    public void removePermission(String userId, String permissionId, String operatorId) {
        // 检查是否存在
        if (!hasUserPermission(userId, permissionId)) {
            throw new RuntimeException("用户权限关联不存在");
        }
        
        userPermissionMapper.deleteByUserIdAndPermissionId(userId, permissionId);
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "REMOVE_USER_PERMISSION",
            "user_permission",
            userId + "-" + permissionId,
            "删除用户权限关联",
            "success",
            operatorId
        );
    }
    
    /**
     * 批量为用户授权权限
     */
    @Transactional
    public void grantPermissions(String userId, List<String> permissionIds, String grantedBy, String reason) {
        for (String permissionId : permissionIds) {
            grantPermission(userId, permissionId, grantedBy, reason);
        }
    }
    
    /**
     * 批量撤销用户权限
     */
    @Transactional
    public void revokePermissions(String userId, List<String> permissionIds, String operatorId, String reason) {
        for (String permissionId : permissionIds) {
            revokePermission(userId, permissionId, operatorId, reason);
        }
    }
    
    /**
     * 更新用户的所有特殊权限
     */
    @Transactional
    public void updateUserPermissions(String userId, List<String> permissionIds, String operatorId, String reason) {
        // 先删除用户的所有特殊权限
        userPermissionMapper.deleteByUserId(userId);
        
        // 再分配新权限
        if (permissionIds != null && !permissionIds.isEmpty()) {
            grantPermissions(userId, permissionIds, operatorId, reason);
        }
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "UPDATE_USER_PERMISSIONS",
            "user",
            userId,
            "更新用户特殊权限，新权限数量: " + (permissionIds != null ? permissionIds.size() : 0),
            "success",
            operatorId
        );
    }
    
    /**
     * 删除用户的所有权限
     */
    @Transactional
    public void removeAllUserPermissions(String userId, String operatorId) {
        int deletedCount = userPermissionMapper.deleteByUserId(userId);
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "REMOVE_ALL_USER_PERMISSIONS",
            "user",
            userId,
            "移除用户的所有特殊权限，共移除: " + deletedCount + " 个权限",
            "success",
            operatorId
        );
    }
    
    /**
     * 删除权限的所有用户关联
     */
    @Transactional
    public void removeAllPermissionUsers(String permissionId, String operatorId) {
        int deletedCount = userPermissionMapper.deleteByPermissionId(permissionId);
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "REMOVE_PERMISSION_USERS",
            "permission",
            permissionId,
            "移除权限的所有用户关联，共移除: " + deletedCount + " 个用户",
            "success",
            operatorId
        );
    }
    
    /**
     * 延长权限有效期
     */
    @Transactional
    public void extendPermission(String id, LocalDateTime newExpiresAt, String operatorId) {
        UserPermission userPermission = userPermissionMapper.selectById(id);
        if (userPermission == null) {
            throw new RuntimeException("用户权限不存在");
        }
        
        LocalDateTime oldExpiresAt = userPermission.getExpiresAt();
        userPermissionMapper.updateExpiresAt(id, newExpiresAt);
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "EXTEND_PERMISSION",
            "user_permission",
            id,
            "延长权限有效期，从 " + oldExpiresAt + " 延长到 " + newExpiresAt,
            "success",
            operatorId
        );
    }
    
    /**
     * 查询临时权限列表
     */
    public List<UserPermission> getTemporaryPermissions(String userId) {
        return userPermissionMapper.selectTemporaryPermissions(userId);
    }
    
    /**
     * 查询过期权限列表
     */
    public List<UserPermission> getExpiredPermissions() {
        return userPermissionMapper.selectExpiredPermissions();
    }
    
    /**
     * 查询即将过期的权限列表
     */
    public List<UserPermission> getExpiringPermissions(Integer days) {
        return userPermissionMapper.selectExpiringPermissions(days);
    }
    
    /**
     * 清理过期权限
     */
    @Transactional
    public int cleanupExpiredPermissions() {
        int cleanedCount = userPermissionMapper.cleanupExpiredPermissions();
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "CLEANUP_EXPIRED_PERMISSIONS",
            "system",
            "expired_permissions",
            "清理过期权限，共清理: " + cleanedCount + " 个权限",
            "success",
            "system"
        );
        
        return cleanedCount;
    }
    
    /**
     * 查询用户权限总数
     */
    public Long getTotalCount() {
        return userPermissionMapper.selectCount();
    }
    
    /**
     * 查询指定用户的权限数量
     */
    public Long getUserPermissionCount(String userId) {
        return userPermissionMapper.selectUserPermissionCount(userId);
    }
    
    /**
     * 查询指定权限的用户数量
     */
    public Long getPermissionUserCount(String permissionId) {
        return userPermissionMapper.selectPermissionUserCount(permissionId);
    }
    
    /**
     * 查询临时权限数量
     */
    public Long getTemporaryPermissionCount() {
        return userPermissionMapper.selectTemporaryPermissionCount();
    }
    
    /**
     * 查询过期权限数量
     */
    public Long getExpiredPermissionCount() {
        return userPermissionMapper.selectExpiredPermissionCount();
    }
    
    /**
     * 查询权限分布统计
     */
    public List<Map<String, Object>> getPermissionDistributionStats() {
        return userPermissionMapper.selectPermissionDistributionStats();
    }
    
    /**
     * 查询用户权限统计
     */
    public List<Map<String, Object>> getUserPermissionStats() {
        return userPermissionMapper.selectUserPermissionStats();
    }
    
    /**
     * 查询最近授权的权限
     */
    public List<UserPermission> getRecentGranted(Integer limit) {
        return userPermissionMapper.selectRecentGranted(limit);
    }
    
    /**
     * 查询指定时间段内的权限授权记录
     */
    public List<UserPermission> getGrantedInPeriod(LocalDateTime startTime, LocalDateTime endTime) {
        return userPermissionMapper.selectGrantedInPeriod(startTime, endTime);
    }
    
    /**
     * 查询没有特殊权限的用户列表
     */
    public List<String> getUsersWithoutSpecialPermission() {
        return userPermissionMapper.selectUsersWithoutSpecialPermission();
    }
    
    /**
     * 查询没有用户的权限列表
     */
    public List<String> getPermissionsWithoutUser() {
        return userPermissionMapper.selectPermissionsWithoutUser();
    }
    
    /**
     * 查询用户权限变更历史
     */
    public List<Map<String, Object>> getUserPermissionHistory(String userId) {
        return userPermissionMapper.selectUserPermissionHistory(userId);
    }
    
    /**
     * 查询权限授权者统计
     */
    public List<Map<String, Object>> getGranterStats() {
        return userPermissionMapper.selectGranterStats();
    }
    
    /**
     * 检查权限授权冲突
     */
    public List<Map<String, Object>> checkPermissionConflicts(String userId, List<String> permissionIds) {
        return userPermissionMapper.checkPermissionConflicts(userId, permissionIds);
    }
    
    /**
     * 查询用户的权限继承链
     */
    public List<Map<String, Object>> getUserPermissionChain(String userId) {
        return userPermissionMapper.selectUserPermissionChain(userId);
    }
    
    /**
     * 查询权限使用频率统计
     */
    public List<Map<String, Object>> getPermissionUsageStats(LocalDateTime startTime, LocalDateTime endTime) {
        return userPermissionMapper.selectPermissionUsageStats(startTime, endTime);
    }
    
    /**
     * 复制用户权限
     */
    @Transactional
    public void copyUserPermissions(String sourceUserId, String targetUserId, String operatorId, String reason) {
        // 获取源用户的特殊权限
        List<String> sourcePermissionIds = getGrantedPermissionIds(sourceUserId);
        
        if (sourcePermissionIds.isEmpty()) {
            throw new RuntimeException("源用户没有任何特殊权限");
        }
        
        // 为目标用户分配相同权限
        updateUserPermissions(targetUserId, sourcePermissionIds, operatorId, reason);
        
        // 记录审计日志
        auditLogHelper.recordLog(
            "COPY_USER_PERMISSIONS",
            "user",
            targetUserId,
            "从用户 " + sourceUserId + " 复制特殊权限到用户 " + targetUserId + "，共复制 " + sourcePermissionIds.size() + " 个权限",
            "success",
            operatorId
        );
    }
}